package com.oswift.cms.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.dao.ChannelDao;
import com.oswift.cms.dao.UserGroupDao;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.UserGroupBean;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;

public class ChannelServiceImpl implements IChannelService
{
    /**
     * ChannelDaoImpl对象注入
     */
    private ChannelDao channelDao;

    /**
     * UserGroupDaoImpl对象注入
     */
    private UserGroupDao userGroupDao;

    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(ChannelServiceImpl.class);

    /**
     *
     * 保存栏目内容
     *
     * @author zhuou
     * @param channelBean
     *            栏目bean
     * @param channelType
     *            栏目类型
     * @return boolean
     * @throws PlatException
     *             CMS公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean save(ChannelBean channelBean, int channelType)
        throws PlatException
    {
        int rows = 0;
        // 计算出channelId
        int channelId = Field.DEFAULT_CHANNELID;
        ChannelBean top1Bean = channelDao.getTop1Channel();
        if (null != top1Bean)
        {
            channelId = top1Bean.getChannelId() + 1;
        }
        channelBean.setChannelId(channelId);

        if (Field.ChannelType.CONTAIN == channelType)
        {
            rows = channelDao.saveContainCh(channelBean);
        }
        else if (Field.ChannelType.SINGLE == channelType)
        {
            rows = channelDao.saveSingleCh(channelBean);
        }
        else if (Field.ChannelType.EXTERNAL == channelType)
        {
            rows = channelDao.saveExternalCh(channelBean);
        }
        else
        {
            log.error("Channel type error, not the channel type. channelType="
                    + channelType);

            return false;
        }

        // 如果有父节点，则将父节点的isChild字段改为true
        if (channelBean.getParentId() != Field.PARENT_ID)
        {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("isChild", true);
            param.put("channelId", channelBean.getParentId());
            rows = channelDao.updateChildFlag(param);
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }

        return rows <= 0 ? false : true;
    }

    /**
     *
     * 修改栏目信息
     *
     * @author zhuou
     * @param channelBean
     *            栏目bean
     * @return boolean
     * @throws PlatException
     *             平台公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean update(ChannelBean channelBean) throws PlatException
    {
        return channelDao.update(channelBean) > 0 ? true : false;
    }

    /**
     *
     * 根据公司Id获取用户组信息
     *
     * @author zhuou
     * @param companyId
     * @return List
     * @throws PlatException
     *             CMS公共异常
     */
    public List<UserGroupBean> getUserGroupByCompanyId(int companyId)
        throws PlatException
    {
        return userGroupDao.getUserGroupByCompanyId(companyId);
    }

    /**
     *
     * 栏目加载server处理方法
     *
     * @author zhuou
     * @param viewName
     *            视图名称
     * @param companyId
     *            公司Id
     * @return ModelAndView
     * @throws PlatException
     *             CMS公共异常
     */
    public ModelAndView loadAddChannel(String viewName, int companyId)
        throws PlatException
    {
        ModelAndView mv = new ModelAndView(viewName);
        mv.addObject("forum", getForumInfo());

        List<UserGroupBean> beanList = userGroupDao
                .getUserGroupByCompanyId(companyId);
        mv.addObject("beans", beanList);

        return mv;
    }

    /**
     *
     * 加载修改栏目页面
     *
     * @author zhuou
     * @param viewName
     *            页面名称
     * @param companyId
     *            单位Id
     * @param channelId
     *            栏目Id
     * @return ModelAndView
     * @throws PlatException
     *             平台公共异常
     */
    public ModelAndView loadUpdateChannel(String viewName, int companyId,
            int channelId) throws PlatException
    {
        ModelAndView mv = new ModelAndView(viewName);
        ChannelBean channel = channelDao.getChannelById(channelId);
        mv.addObject("channel", channel);

        String sForums = channel.getForums();
        List<DictionaryBean> forumsList = getForumInfo();
        if (!StringUtil.isBlank(sForums))
        {
            String[] aForums = sForums.split(",");
            for (DictionaryBean item1 : forumsList)
            {
                for (String item2 : aForums)
                {
                    if (item1.getFieldValue().equals(item2))
                    {
                        item1.setChecked(true);
                        break;
                    }
                }
            }
        }
        mv.addObject("forum", forumsList);

        List<UserGroupBean> beanList = userGroupDao
                .getUserGroupByCompanyId(companyId);
        mv.addObject("beans", beanList);

        return mv;
    }

    /**
     *
     * 获取板块信息
     *
     * @author zhuou
     * @return List<DictionaryBean>
     */
    public List<DictionaryBean> getForumInfo()
    {
        List<DictionaryBean> beanList = new ArrayList<DictionaryBean>();

        DictionaryBean bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ANNOUNCE_KEY);
        beanList.add(getNewObject(bean));

        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ARTICLE_KEY);
        beanList.add(getNewObject(bean));

        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_GUESTBOOK_KEY);
        beanList.add(getNewObject(bean));

        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_PICURL_KEY);
        beanList.add(getNewObject(bean));

        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_DOWNLOAD_KEY);
        beanList.add(getNewObject(bean));

        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_FRIENDSITE_KEY);
        beanList.add(getNewObject(bean));

        return beanList;
    }

    /**
     *
     * 生产一个新对象
     *
     * @author zhuou
     * @param bean
     *            旧的DictionaryBean
     * @return DictionaryBean
     */
    private DictionaryBean getNewObject(DictionaryBean bean)
    {
        DictionaryBean newBean = new DictionaryBean();
        newBean.setCache(bean.isCache());
        newBean.setChecked(bean.isChecked());
        newBean.setFieldID(bean.getFieldID());
        newBean.setFieldName(bean.getFieldName());
        newBean.setFieldValue(bean.getFieldValue());
        newBean.setTitle(bean.getTitle());

        return newBean;
    }

    /**
     *
     * 根据公司ID查询栏目
     *
     * @author zhuou
     * @param companyId
     *            公司Id
     * @return ModelAndView
     * @throws PlatException
     *             CMS公共异常
     */
    public ModelAndView getChannelByCompanyId(int companyId)
        throws PlatException
    {
        ModelAndView mv = new ModelAndView();
        List<ChannelBean> bean = channelDao.getChannelByCompanyId(companyId);
        mv.addObject("list", bean);
        mv.addObject("listNum", bean.size());

        return mv;
    }

    /**
     *
     * 获取channel详情
     *
     * @author zhuou
     * @param channelId
     * @param view
     *            页面名称
     * @return ModelAndView
     * @throws PlatException
     *             CMS公共异常
     */
    public ModelAndView getChannelById(int channelId, String view,
            String errorPage) throws PlatException
    {
        ModelAndView mv = null;
        if (channelId <= 0 || StringUtil.isEmpty(view))
        {
            mv = new ModelAndView(errorPage);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.GET_WEBPARAM_FAIL);
            bean.setMessInfo(ResourceManager
                    .getValue(PageCode.GET_WEBPARAM_FAIL));
            return mv;
        }

        mv = new ModelAndView(view);
        ChannelBean bean1 = channelDao.getChannelById(channelId);
        if (bean1.getParentId() > 0)
        {
            ChannelBean bean2 = channelDao.getChannelById(bean1.getParentId());
            mv.addObject("parent", bean2);
        }

        String st = bean1.getForums();
        List<DictionaryBean> dList = getForumInfo();
        if (!StringUtil.isEmpty(st))
        {
            for (DictionaryBean d : dList)
            {
                if (-1 != st.indexOf(d.getFieldValue()))
                {
                    st = st.replace(d.getFieldValue(), d.getTitle() + "<br/>");
                }
            }
        }
        bean1.setForums(st);
        mv.addObject("channel", bean1);
        return mv;
    }

    /**
     *
     * 根据parentId获取栏目信息
     *
     * @author zhuou
     * @param parentId
     * @return List<ChannelBean>
     * @throws PlatException
     *             CMS公共异常
     */
    public List<ChannelBean> getChannelListByParentId(int parentId)
        throws PlatException
    {
        return channelDao.getChannelListByParentId(parentId);
    }

    /**
     *
     * 查询栏目信息，当companyId=-1时查询全部栏目，如果>1则查询相关公司栏目信息
     *
     * @author zhuou
     * @param companyId
     *            公司ID
     * @param keyword
     *            查询关键字
     * @param rowNum
     *            行数
     * @param pageNum
     *            每页显示记录数
     * @return PageBean
     * @throws PlatException
     *             CMS公共异常
     */
    public PageBean<ChannelBean> getChannelList(int companyId, String keyword,
            int pageNum, int pageRecordNum) throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        return channelDao.getChannelList(companyId, keyword, rowNum,
                pageRecordNum);
    }

    /**
     *
     * 根据公司ID和forums板块查询栏目列表
     *
     * @author zhuou
     * @param companyId
     * @param forums
     * @return ModelAndView
     * @throws PlatException
     *             CMS公共异常
     */
    public ModelAndView getChannel2(int companyId, String forums)
        throws PlatException
    {
        ModelAndView mv = new ModelAndView();
        List<ChannelBean> bean = channelDao.getChannel2(companyId, forums);
        mv.addObject("list", bean);

        // 获取默认栏目
        ChannelBean defaultChannel = channelDao.getDefaultChannel(companyId,
                forums);
        mv.addObject("defaultChannel", defaultChannel);
        return mv;
    }

    /**
     *
     * 根据公司ID和forums板块查询栏目列表
     *
     * @author zhuou
     * @param companyId
     * @param forums
     * @return List<ChannelBean>
     * @throws PlatException
     *             CMS公共异常
     */
    public List<ChannelBean> getChannelList2(int companyId, String forums)
        throws PlatException
    {
        return channelDao.getChannel2(companyId, forums);
    }

    /**
     *
     * 删除栏目时，会相应修改内容栏目ID字段值
     *
     * @author zhuou
     * @param channelId
     *            栏目ID
     * @param companyId
     *            单位Id
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean delChannel(int channelId, int companyId)
        throws PlatException
    {
        ChannelBean cBean = channelDao.getChannelById(channelId);
        if (cBean == null)
        {
            throw new PlatException(PageCode.CHANNEL_ISONT_EXIST);
        }

        // 获取和被删除节点相同层次的节点
        List<ChannelBean> sameNodes = channelDao.getChannelListByParentId(cBean
                .getParentId());

        // 删除操作
        int rows = channelDao.delete(channelId);
        if (rows != 1)
        {
            throw new PlatException(PageCode.CHANNEL_DEL_FAIL);
        }

        // 修改删除栏目节点的子节点或者父节点的isChild字段
        if (cBean.getParentId() != Field.PARENT_ID)
        {
            // 如果被删除的栏目有子节点，则不做操作
            if (!cBean.isChild())
            {
                // 如果小于等于1，则表明父节点只有被删除的这个节点一个子节点，那么要将父节点isChild=false
                if (sameNodes.size() <= 1)
                {
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("isChild", false);
                    param.put("channelId", cBean.getParentId());
                    rows = channelDao.updateChildFlag(param);
                    if (rows <= 0)
                    {
                        throw new PlatException(ErrorCode.COMMON_DB_ERROR);
                    }
                }
            }
        }

        // 查出所有子栏目,将子栏目的
        List<ChannelBean> childList = channelDao
                .getChannelListByParentId(channelId);
        if (null != childList && !childList.isEmpty())
        {
            // 修改此栏目的子栏目的ParentId
            rows = channelDao.updateParentId(channelId, cBean.getParentId());
            if (rows <= 0)
            {
                throw new PlatException(PageCode.CHANNEL_DEL_FAIL);
            }
        }

        // 将和此栏目关联的内容channelId改为默认栏目Id
        updateContentChannelId(channelId, companyId);

        return true;
    }

    /**
     *
     * 删除栏目时，要将和此栏目关联的内容channelId改为默认栏目Id
     *
     * @author zhuou
     * @param channelId
     *            栏目Id
     * @param companyId
     *            公司Id
     * @throws PlatException
     *             公共异常
     */
    private void updateContentChannelId(int channelId, int companyId)
        throws PlatException
    {
        // 将公告内容的栏目节点赋值为默认公告栏目节点ID
        DictionaryBean bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ANNOUNCE_KEY);
        ChannelBean defaultChannel = channelDao.getDefaultChannel(companyId,
                bean.getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.ANNOUNCE);

        // 修改文章内容栏目Id
        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ARTICLE_KEY);
        defaultChannel = channelDao.getDefaultChannel(companyId, bean
                .getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.ARTICLE);

        // 修改留言内容Id
        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_GUESTBOOK_KEY);
        defaultChannel = channelDao.getDefaultChannel(companyId, bean
                .getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.GUESTBOOK);

        // 修改图片内容Id
        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_PICURL_KEY);
        defaultChannel = channelDao.getDefaultChannel(companyId, bean
                .getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.PICURL);

        // 修改下载内容Id
        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_DOWNLOAD_KEY);
        defaultChannel = channelDao.getDefaultChannel(companyId, bean
                .getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.DOWNLOAD);

        // 修改友情链接内容Id
        bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_FRIENDSITE_KEY);
        defaultChannel = channelDao.getDefaultChannel(companyId, bean
                .getFieldValue());
        channelDao.updateCommonModel(defaultChannel.getChannelId(), channelId,
                Field.TableName.FRIENDSITE);
    }

    /**
     *
     * 根据公司ID查询出没有外接栏目的所有栏目
     *
     * @author zhuou
     * @param companyId
     *            公司ID
     * @return list
     * @throws PlatException
     *             CMS公共异常
     */
    public List<ChannelBean> getChannel3(int companyId) throws PlatException
    {
        return channelDao.getChannel3(companyId);
    }

    public ChannelDao getChannelDao()
    {
        return channelDao;
    }

    public void setChannelDao(ChannelDao channelDao)
    {
        this.channelDao = channelDao;
    }

    public UserGroupDao getUserGroupDao()
    {
        return userGroupDao;
    }

    public void setUserGroupDao(UserGroupDao userGroupDao)
    {
        this.userGroupDao = userGroupDao;
    }
}
